<template>
  <div class="order-cancel-container">
    <!-- 顶部导航 -->
    <header class="cancel-header">
      <button class="back-btn" @click="handleBack">
        <i class="fa fa-arrow-left"></i> 返回
      </button>
      <h2>取消订单与退款</h2>
    </header>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-state">
      <i class="fa fa-circle-o-notch fa-spin"></i>
      <p>处理中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-if="!isLoading && errorMessage" class="error-state">
      <i class="fa fa-exclamation-circle"></i>
      <p>{{ errorMessage }}</p>
      <button class="retry-btn" @click="handleCancelOrder">重新尝试</button>
      <button class="back-btn" @click="handleBack">返回订单详情</button>
    </div>

    <!-- 退款成功状态 -->
    <div v-if="!isLoading && !errorMessage && refundSuccess" class="success-state">
      <i class="fa fa-check-circle"></i>
      <h3>操作成功</h3>
      <p>{{ refundResult.detail }}</p>
      <div class="refund-info" v-if="refundResult.refund_amount">
        <p>退款金额：<span class="amount">¥{{ formatPrice(refundResult.refund_amount) }}</span></p>
        <p>支付宝交易号：<span class="trade-id">{{ refundResult.alipay_trade_id || '未知' }}</span></p>
        <p>预计到账时间：1-3个工作日（具体以支付渠道为准）</p>
      </div>
      <button class="to-list-btn" @click="goToOrderList">查看我的订单</button>
    </div>

    <!-- 确认取消订单表单 -->
    <div v-if="!isLoading && !errorMessage && !refundSuccess" class="cancel-form">
      <div class="order-summary">
        <h3>订单信息确认</h3>
        <p>订单编号：{{ orderId }}</p>
        <p>当前状态：{{ getStatusText(orderStatus) }}</p>
        <p>订单金额：<span class="price">¥{{ formatPrice(orderSum) }}</span></p>
        <p v-if="needRefund" class="refund-notice">
          <i class="fa fa-info-circle"></i> 该订单已支付，取消后将自动发起退款
        </p>
      </div>

      <div class="cancel-reason">
        <h3>取消原因</h3>
        <textarea 
          v-model="cancelReason" 
          placeholder="请输入取消订单的原因（选填）"
          maxlength="200"
          :disabled="isProcessing"
        ></textarea>
        <p class="word-count">{{ cancelReason.length }}/200</p>
      </div>

      <button 
        class="confirm-btn" 
        @click="handleCancelOrder"
        :disabled="isProcessing"
      >
        <i class="fa fa-check"></i>
        <span v-if="isProcessing">处理中...</span>
        <span v-else>确认取消订单</span>
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, toRefs } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';

// 路由实例
const router = useRouter();
const route = useRoute();

// 状态管理
const state = reactive({
  isLoading: false,
  isProcessing: false,
  errorMessage: '',
  refundSuccess: false,
  refundResult: {},
  cancelReason: '',
  orderId: '',
  orderSum: 0,
  orderStatus: '',
  needRefund: false, // 是否需要退款

  // 订单状态映射
  orderStatusMap: {
    '1': '待支付',
    '2': '待接单',
    '3': '待派送',
    '4': '派送中',
    '5': '已完成',
    '6': '已取消',
    '7': '取消中'
  }
});

const {
  isLoading, isProcessing, errorMessage, refundSuccess, refundResult,
  cancelReason, orderId, orderSum, orderStatus, needRefund, orderStatusMap
} = toRefs(state);

// 初始化
onMounted(() => {
  // 从路由参数获取订单信息
  orderId.value = route.params.id;
  orderSum.value = route.query.sum || 0;
  orderStatus.value = route.query.status || '';
  
  // 判断是否需要退款（已支付状态）
  needRefund.value = [3, 4, 5].includes(Number(orderStatus.value));
});

/**
 * 处理取消订单请求
 */
const handleCancelOrder = async () => {
  if (!confirm('确定要取消订单吗？')) {
    return;
  }

  try {
    isProcessing.value = true;
    errorMessage.value = '';

    // 调用取消订单接口
    const response = await axios.put(`/order/order/${orderId.value}/cancel/`, {
      reason: cancelReason.value // 可选：取消原因
    });

    // 保存退款结果
    refundResult.value = response.data;
    refundSuccess.value = true;
  } catch (err) {
    errorMessage.value = err.response?.data?.message || '取消订单失败，请重试';
    console.error('取消订单错误:', err);
  } finally {
    isProcessing.value = false;
  }
};

/**
 * 获取订单状态文本
 */
const getStatusText = (status) => {
  return orderStatusMap.value[status] || `未知状态(${status})`;
};

/**
 * 格式化价格
 */
const formatPrice = (price) => {
  const numericPrice = Number(price);
  return isNaN(numericPrice) ? '0.00' : numericPrice.toFixed(2);
};

/**
 * 返回上一页
 */
const handleBack = () => {
  router.back();
};

/**
 * 前往订单列表
 */
const goToOrderList = () => {
  router.push('/order');
};
</script>

<style scoped>
.order-cancel-container {
  min-height: 100vh;
  background-color: #f9f9f9;
  color: #333;
  padding-bottom: 30px;
}

/* 头部导航 */
.cancel-header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background-color: white;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.back-btn {
  background: none;
  border: none;
  font-size: 18px;
  color: #333;
  cursor: pointer;
  margin-right: 15px;
}

.cancel-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 100px 0;
  color: #666;
}

.loading-state i {
  font-size: 50px;
  margin-bottom: 20px;
  color: #ff7a5a;
  animation: spin 1.5s linear infinite;
}

/* 错误状态 */
.error-state {
  background-color: #ffebee;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  color: #b71c1c;
  margin: 20px;
}

.error-state i {
  font-size: 60px;
  margin-bottom: 20px;
}

.error-state p {
  margin: 0 0 30px 0;
  font-size: 16px;
}

.error-state .retry-btn {
  background-color: #ff7a5a;
  color: white;
  border: none;
  padding: 10px 25px;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
}

.error-state .back-btn {
  background-color: #fff;
  color: #666;
  border: 1px solid #ddd;
  padding: 10px 25px;
  border-radius: 4px;
  cursor: pointer;
}

/* 成功状态 */
.success-state {
  background-color: #e8f5e9;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  color: #2e7d32;
  margin: 20px;
}

.success-state i {
  font-size: 60px;
  margin-bottom: 20px;
  color: #4caf50;
}

.success-state h3 {
  margin: 0 0 15px 0;
  font-size: 20px;
}

.success-state p {
  margin: 10px 0;
  font-size: 15px;
}

.refund-info {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 6px;
  padding: 15px;
  margin: 20px auto;
  max-width: 500px;
  text-align: left;
}

.amount {
  color: #e53935;
  font-weight: bold;
}

.trade-id {
  font-family: monospace;
  word-break: break-all;
}

.to-list-btn {
  background-color: #4caf50;
  color: white;
  border: none;
  padding: 10px 30px;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 20px;
  font-size: 16px;
}

/* 表单样式 */
.cancel-form {
  background-color: white;
  margin: 20px;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.order-summary {
  padding-bottom: 20px;
  border-bottom: 1px solid #f5f5f5;
  margin-bottom: 20px;
}

.order-summary h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #555;
  display: flex;
  align-items: center;
  gap: 8px;
}

.order-summary h3::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #ff7a5a;
  border-radius: 2px;
}

.order-summary p {
  margin: 8px 0;
  font-size: 14px;
}

.price {
  color: #e53935;
  font-weight: bold;
}

.refund-notice {
  color: #1976d2;
  background-color: #e3f2fd;
  padding: 10px;
  border-radius: 4px;
  margin-top: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.cancel-reason {
  margin-bottom: 30px;
}

.cancel-reason h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #555;
}

.cancel-reason textarea {
  width: 100%;
  min-height: 100px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  font-size: 14px;
  box-sizing: border-box;
}

.word-count {
  text-align: right;
  color: #999;
  font-size: 12px;
  margin: 5px 0 0 0;
}

.confirm-btn {
  width: 100%;
  padding: 12px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: background-color 0.3s;
}

.confirm-btn:hover {
  background-color: #d32f2f;
}

.confirm-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .error-state {
    padding: 30px 15px;
  }
  
  .success-state {
    padding: 30px 15px;
  }
  
  .error-state .retry-btn,
  .error-state .back-btn {
    width: 100%;
    margin: 5px 0;
  }
}
</style>